#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author : bird.zhang@ximalaya.com

import base64
from Crypto.Cipher import AES


def refactor_key(text):
    """
    这里密钥key 长度必须为16（AES-128）、24（AES-192）、或32（AES-256）Bytes 长度.目前AES-128足够用
    :param text:
    :return:
    """

    text_bytes = bytes(text, 'utf-8')
    # 不能超过32位
    count = len(text_bytes)

    if 0 == count:
        return b'\0' * 16
    elif 0 < count < 16:
        return text_bytes + (b'\0' * (16 - count))
    elif 16 == count:
        return text_bytes
    elif 16 < count < 24:
        return text_bytes + (b'\0' * (24 - count))
    elif 24 == count:
        return text_bytes
    elif 24 < count < 32:
        return text_bytes + (b'\0' * (32 - count))
    else:
        return text_bytes[:32]


def refactor_message(message):
    """
    重构message，将其变成16的倍数的bytes，默认utf-8编码
    :param message: 明文
    :return: 长度是16倍数的bytes
    """

    message_bytes = bytes(message, 'utf-8')
    length = 16
    count = len(message_bytes)
    if 0 == count % length:
        return message_bytes
    else:
        add = length - (count % length)
        message_bytes = message_bytes + (b'\0' * add)
        return message_bytes


class Cryptor:
    """
    封装AES.MODE_CBC
    """

    def __init__(self, key):
        self.key = refactor_key(key)
        self.iv = self.key[:16]
        self.mode = AES.MODE_CBC

    def encrypt(self, message):
        cryptor = AES.new(self.key, self.mode, self.iv)
        message = refactor_message(message)
        ciphertext = cryptor.encrypt(message)
        # 加密后的密文是bytes
        # print(type(ciphertext))
        # 因为AES加密时候得到的字符串不一定是ascii字符集的，输出到终端或者保存时候可能存在问题
        # 所以这里统一把加密后的字符串转化为16进制字符串
        return str(base64.b64encode(ciphertext), 'utf-8')
        # return b2a_hex(ciphertext).decode("ASCII")

    def decrypt(self, ciphertext):
        cryptor = AES.new(self.key, self.mode, self.iv)
        # 解密后，去掉补足的空格用strip() 去掉
        plain_text = cryptor.decrypt(base64.b64decode(ciphertext))
        return plain_text.rstrip(b'\0').decode("utf-8")


if __name__ == '__main__':
    pc = Cryptor('keysskkeyskeysagdfahdghkkhhgoiijjaslkjgafkjgljlk;djhjj;ljlj')  # 初始化密钥
    e = pc.encrypt("my book is free")
    d = pc.decrypt(e)
    print((e, d))
    e = pc.encrypt("我是一个粉刷匠1231繁體testひらがな")
    d = pc.decrypt(e)
    print((e, d))
